package tgc.edu.tms.web.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.tms.custom.TablePageable;
import tgc.edu.tms.entity.TbClass;
import tgc.edu.tms.entity.Teacher;
import tgc.edu.tms.entity.Teaching;
import tgc.edu.tms.entity.Worksheet;
import tgc.edu.tms.service.TeacherService;
import tgc.edu.tms.service.TeachingService;
import tgc.edu.tms.web.form.WorksheetForm;

@Controller
@RequestMapping(value="/worksheet")
public class WorksheetController{

	@Autowired
	private TeachingService teachingService;
	
	@Autowired
	private TeacherService teacherService;
	
	@RequestMapping(value="/manage")
	public void manage(ModelMap map) {
	
	}
	
	@RequestMapping(value="/page")
	@ResponseBody
	public Object page(TablePageable pageParam,WorksheetForm form) {
		// PageRequest pageable = pageParam.bulidPageRequest();
        if(!StringUtils.hasText(form.getTime())) {
            DateFormat format = new SimpleDateFormat("yyyy-MM");
            form.setTime(format.format(new Date()));
        }
        System.out.println("查询时间："+form.getTime());
		HashMap<String, Object> result=new HashMap<>();
		List<Teacher> all = teacherService.findAll();
		
		Integer count = 0;
		
		// HashMap<String, Object> content = new HashMap<>();
		List<Worksheet> content = new ArrayList<>();
		for (Teacher teacher : all) {
		    // 设置教师对象
		    form.setTeacher(teacher);
		    // 设置教师id
		    form.setTeacherId(teacher.getId());
		    /**
		     * 当前老师授课记录 去重
		     * 当前 安全查询 Spec 已设置参数
		     *    - time：格式：2018-12 或 2018-01
		     *    - teacher： 一个 Teacher 对象
		     *    - teacherId: 教师Id
		     */
		    List<Teaching> oneTeacherTeachingList = teachingService.findAll(buildSpec(form));// 一个老师的所有授课记录
		    Boolean flag = false;
		    List<Teaching> ting2 = new ArrayList<>();
		    for(int i = 0; i < oneTeacherTeachingList.size(); i ++) {
                Teacher teacher1 = oneTeacherTeachingList.get(i).getTeachingplan().getTeacher();
                List<TbClass> tbclass1 = oneTeacherTeachingList.get(i).getKc().getTbclass();
                
                for (int j = 0; j < ting2.size(); j++) {
                    Teacher teacher2 = ting2.get(j).getTeachingplan().getTeacher();
                    List<TbClass> tbclass2 = ting2.get(j).getKc().getTbclass();
                    if(teacher1.equals(teacher2) && tbclass1.equals(tbclass2)) {
                        flag = true;
                        break;
                    }
                }
                if(!flag) {
                    ting2.add(oneTeacherTeachingList.get(i));
                }
		    }
		    
		    /**
		     * 当前老师的某一个班级的数据整合
		     */
		    for (Teaching t2 : ting2) {
		        
		        Worksheet worksheet = new Worksheet();
		        
		        System.out.println("当前老师:"+t2.getTeachingplan().getTeacherName()
		                +", 当前班级："+t2.getKc().getTbclassName());
		        
		        Integer teacherId1 = t2.getTeachingplan().getTeacher().getId();
		        List<TbClass> tbclass1 = t2.getKc().getTbclass();
                System.out.println("ting.size:"+ting2.size());
                /**
                 * 当前老师在当月当前班级的数据统计
                 */
                for(int i = 0; i < oneTeacherTeachingList.size(); i ++) {
                    Teaching teaching = oneTeacherTeachingList.get(i);
                    Integer teacherId2 = teaching.getTeachingplan().getTeacher().getId();
                    List<TbClass> tbclass2 = teaching.getKc().getTbclass();
                    Integer monthperiod = 0;// 月分班学时
                    if(teacherId1.equals(teacherId2) && tbclass1.equals(tbclass2)) {
                        // 合班 OR 分班
                        if(tbclass2.size() > 1) {
                            // System.out.println("当前班级："+teaching.getKc().getTbclassName()+"是合班");
                        } else {
                            // System.out.println("分班");
                        }
                        monthperiod += 1;
                    }
                    worksheet.setMonthperiod(monthperiod);
                    System.out.println("月分班学时："+monthperiod);
                    count += 1;
                    // Id
                    worksheet.setId(count);
                    // 时间
                    worksheet.setTime(teaching.getTime());
                    // 老师
                    worksheet.setTeacher(teaching.getTeachingplan().getTeacher());
                    // 班级名称
                    worksheet.setTbclassname(teaching.getKc().getTbclassName());
                }
                
                content.add(worksheet);
            }
		    
		    /*for(int i = 0; i < ting2.size(); i ++) {
		        Teaching teaching = ting2.get(i);
		        Teacher teacher2 = teaching.getTeachingplan().getTeacher();
		        List<TbClass> tbclass2 = teaching.getKc().getTbclass();
		        form.setTeacher(teacher2);
		        form.setTbclass(tbclass2);
		        List<Teaching> findAll = teachingService.findAll(buildSpec(form));
		    }*/
		    
		}
		result.put("total", count);
		result.put("rows", content);
		return result;
	}

	private Specification<Teaching> buildSpec(WorksheetForm form) {
		Specification<Teaching> spec = new Specification<Teaching>() {
			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<Teaching> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();
				String time = form.getTime();
				if(StringUtils.hasText(time)) {
				    rules.add(cb.like(root.get("time"), "%"+time+"%"));
				}
				
				if(form.getTeacherId() != null) {
				    rules.add(cb.equal(root.get("teachingplan").get("teacher").get("id"), form.getTeacherId()));
				}
				
				return cb.and(rules.toArray(new Predicate[rules.size()]));
				
			}
		};
		return spec;
	}
	
}
